﻿using DependencyInjectionHelperLib;
using MeterReader.Common.Config;
using MeterReader.Common.Helpers;
using MeterReader.Models;
using MeterReader.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NLog.Extensions.Logging;
using System.Windows;

namespace MeterReader
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static Mutex? _mutex;

        public App()
        { }

        protected override void OnStartup(StartupEventArgs e)
        {
            _mutex = new Mutex(true, "OnlyRun_CRNS");
            // 防止多次启动
            if (_mutex.WaitOne(0, false))
            {
                try
                {
                    base.OnStartup(e);
                    // 初始化线程更新助手
                    DispatcherHelper.Initialize();
                    // 读取配置文件
                    var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().Get<Config>();
                    GlobalSettings.MaxMaxSeriesPonts = config!.MaxSeriesPonts;
                    // 注册服务
                    DIContainer.Default.RegisterAndBuildServices(
                        (s) =>
                        {
                            // 虚拟数据，后期换成modbus
                            s.AddSingleton<IDataService, SimDBReadService>()
                                .AddLogging(b => b.AddNLog())
                                // 读取数据注册,后期改成Modubus
                                .AddDbContext<SimMeterDBContext>((s, options) => options.UseSqlite(config.FromConnectionString))
                                // 注册写入的数据库
                                .AddDbContext<MeterDBContext>((s, options) => options.UseSqlite(config.ToConnectionString));
                        }
                    );

                    // 创建数据库
                    using (var scope = DIContainer.Default.GetServiceProvider().CreateScope())
                    {
                        var context = scope.ServiceProvider.GetRequiredService<MeterDBContext>();
                        context.Database.EnsureCreated(); // 创建数据库
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"程序加载异常：{ex.Message}", "加载异常");
                }
            }
            else
            {
                MessageBox.Show("程序已在运行中！", "重复打开提示");
                Shutdown();
            }
        }
    }
}